import pygame
import random
import math

class Particle:
    def __init__(self, x, y, color, size=3, lifetime=60):
        self.x = x
        self.y = y
        self.color = color
        self.size = size
        self.original_size = size
        self.lifetime = lifetime
        self.max_lifetime = lifetime
        
        # 随机速度和方向
        angle = random.uniform(0, 2 * math.pi)
        speed = random.uniform(2, 8)
        self.velocity_x = math.cos(angle) * speed
        self.velocity_y = math.sin(angle) * speed
        
        # 重力和阻力
        self.gravity = 0.3
        self.drag = 0.98

    def update(self):
        """更新粒子状态"""
        self.velocity_y += self.gravity
        self.velocity_x *= self.drag
        self.velocity_y *= self.drag
        
        self.x += self.velocity_x
        self.y += self.velocity_y
        
        # 逐渐缩小粒子
        self.lifetime -= 1
        self.size = self.original_size * (self.lifetime / self.max_lifetime)
        
        return self.lifetime > 0

    def draw(self, screen):
        """绘制粒子"""
        if self.size >= 1:
            pygame.draw.circle(screen, self.color, 
                             (int(self.x), int(self.y)), 
                             int(self.size))

class ParticleSystem:
    def __init__(self):
        self.particles = []

    def create_explosion(self, x, y, color, particle_count=20):
        """创建爆炸效果"""
        for _ in range(particle_count):
            particle = Particle(x, y, color)
            self.particles.append(particle)

    def create_impact(self, x, y, color, velocity_x=0, velocity_y=0):
        """创建撞击效果"""
        for _ in range(10):
            particle = Particle(x, y, color, size=2, lifetime=30)
            # 根据撞击方向调整粒子初始速度
            particle.velocity_x += velocity_x * 0.3
            particle.velocity_y += velocity_y * 0.3
            self.particles.append(particle)

    def create_trail(self, x, y, color):
        """创建拖尾效果"""
        particle = Particle(x, y, color, size=2, lifetime=20)
        particle.gravity = 0.1  # 较小的重力效果
        self.particles.append(particle)

    def update(self):
        """更新所有粒子"""
        self.particles = [p for p in self.particles if p.update()]

    def draw(self, screen):
        """绘制所有粒子"""
        for particle in self.particles:
            particle.draw(screen)